<?php
declare (strict_types=1);

namespace app\exam\logic;

use think\facade\Db;
use think\facade\Cache;
use app\common\exception\LogicException;
use app\exam\model\SpecialTopic as SpecialTopicModel;

/**
 * 专项练习试题关联逻辑
 */
class SpecialTopic extends SpecialTopicModel
{
	/**
	 * 
	 * Author 亓官雨树<lucky.max@foxmail.com>
	 * Date 2021-02-04
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function getSpecialTopicBase(array $last_ids)
	{
		$redis  	= Cache::store('redis')->handler();
		$ids 		= $this->whereSpecialId('IN', $last_ids)->column('topic_id');
		$last_ids 	= implode(',', $last_ids);
		$ids 		= implode(',', $ids);
		$data 		= app(Topic::class)->withoutGlobalScope()->alias('t')
			->join('exam_module_special_topic s', "s.special_id IN ({$last_ids}) AND s.topic_id=t.id AND t.id IN ({$ids})")
			->field("t.id,t.question_type,s.special_id")
			->select();

		$list 			= [];
		$answered_num 	= 0;

		foreach ($data as $val) {

			$has_answered 	= 0;
			$answer_data 	= [];
			
			$res 	= $redis->hGet('special_topic_practice', request()->mid.'_'. $val->special_id);
			if ( $res ) {
				$res 			= unserialize($res);
				$has_answered 	= isset($res[$val->id]) ? 1 : 0;
				$answer_data  	= $res[$val->id]??[];
			}

			$has_answered && $answered_num 	+= 1;

			if ( array_key_exists($val->question_type, $list) ) {
				$list[$val->question_type]['num'] 			+= 1;
			} else {
				$list[$val->question_type]['title'] 		= $val->question_type_text;
				$list[$val->question_type]['question_type'] = $val->question_type;
				$list[$val->question_type]['num'] 			= 1;
			}
			$list[$val->question_type]['data'][$val->id] = [
				'special_id' 	=> $val->special_id,
				'topic_id' 		=> $val->id,
				'has_answered'	=> $has_answered,
				'answer_right'  => $answer_data['is_right']??0,
				'answer_data'	=> $answer_data['answer']??[],
			];
			$list[$val->question_type]['data'] = array_values($list[$val->question_type]['data']);
		}
		ksort($list);
		return ['topic_num' => count($data), 'answered_num' => $answered_num, 'rules' => array_values($list)];
	}
}